<template>
  <ul class="list">
    <li
      class="item"
      v-for="item of letters"
      :key="item"
      :ref="item"
      @touchstart.prevent="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      @click="handleLetterClick"
    >{{item}}</li>
  </ul>
</template>
<script>
export default {
  name: "CityAlphabet",
  props: {
    cities: Object
  },
  data() {
    return {
      touchStatus: false,
      startY:0,
      timer:null
    }
  },
  updated() {
      this.startY=this.$refs["A"][0].offsetTop
  },
  computed: {
    letters() {
      const letters = [];
      for (let i in this.cities) {
        letters.push(i);
      }
      return letters;
    }
  },
  methods: {
    handleLetterClick(e) {
      this.$emit("change", e.target.innerText);
      //   console.log(e.target.innerText)  //获取当前点击的字母
    },
    handleTouchStart() {
      this.touchStatus = true;
    },
    // 思路，当手指在上下滑动时，现在是处于哪个字母就对应哪个字母开头的城市
    // 1、先求得A距离顶部(蓝色下边框的位置)，再求得此时手指所在地方距离顶部的位置。再相减。得到的距离除每个
    // 字母的行高。算错此时所在位置，再传递给父组件。
    handleTouchMove(e) {
      if (this.touchStatus) {
        //   截流方法，节约handleTouchMove 执行频率。从而提高性能
          if(this.timer){
              clearTimeout(this.timer)
          }
          this.timer=setTimeout(() => {
                 // touches[0]  代表手指移动信息
        const touchY = e.touches[0].clientY - 79;
        const index = Math.floor((touchY - this.startY) / 20);
        if (index >= 0 && index < this.letters.length) {
          this.$emit("change", this.letters[index]);
        //   console.log(e)
        }
          }, 16);
     
      }
    },
    handleTouchEnd() {
      this.touchStatus = false;
    }
  }
};
</script>
<style lang="stylus" scoped>
@import '~styles/varibles.styl';

.list {
  display: flex;
  flex-direction: column;
  justify-content: center;
  position: absolute;
  top: 1.58rem;
  right: 0;
  bottom: 0;
  width: 0.4rem;

  .item {
    line-height: 0.4rem;
    text-align: center;
    color: $bgColor;
  }
}
</style>
